package com.heima.test;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;

public class Demo2 {
	@Test
	public void demo1() throws Exception{
		Directory directory = FSDirectory.open(new File("F:\\index2"));
		Analyzer analyzer = new StandardAnalyzer();
		IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LATEST, analyzer);
		IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
		File dir = new File("C:\\Users\\Administrator\\Desktop\\自己笔记");
		for(File f : dir.listFiles()){
			Field filename =  new TextField("filename", f.getName(), Store.YES);
			Field filepath = new StoredField("filepath", f.getPath());
			Field filecontent = new TextField("filecontent", FileUtils.readFileToString(f), Store.NO);
			Field filesize = new LongField("filesize", FileUtils.sizeOf(f), Store.YES);
			Document document = new Document();
			document.add(filesize);
			document.add(filecontent);
			document.add(filepath);
			document.add(filename);
			indexWriter.addDocument(document);
		}
		indexWriter.close();
	}
	@Test
	public void demo2() throws Exception{
		Directory directory = FSDirectory.open(new File("F:\\index2"));
		IndexReader indexReader = DirectoryReader.open(directory);
		IndexSearcher indexSearcher = new IndexSearcher(indexReader);
		Query query = new TermQuery(new Term("filename", "day14.txt"));
		TopDocs topDocs = indexSearcher.search(query, 10);
		System.out.println(topDocs.totalHits);
		for (ScoreDoc s : topDocs.scoreDocs) {
			Document doc = indexSearcher.doc(s.doc);
			System.out.println("文件名是:"+doc.getField("filename"));
			
		}
		indexReader.close();
	}
}
